#include "Stdafx.h"
#include "Entity.h"

using namespace SNMP;

Entity::Entity(void){}

Entity::Entity(HSNMP_SESSION hSession, HSNMP_ENTITY hEntity)
{
	this->m_hSession = hSession;
	this->m_hEntity = hEntity;
}

Entity::~Entity(void)
{
	SnmpFreeEntity(this->m_hEntity);
}

void Entity::Clear(void)
{
	SnmpFreeEntity(this->m_hEntity);
	//SNMPAPI_STATUS status = SnmpFreeEntity(this->m_hEntity);
	/*
	if(status == SNMPAPI_FAILURE)
	{
		status = SnmpGetLastError(NULL);
		SNMPManager::ErrorManage(status);
	}
	*/
}

void Entity::CreateEntityHandle(HSNMP_SESSION hSession, System::String^ IPAddress, unsigned long timeout, unsigned long retry)
{
	this->m_hSession = hSession;
	SNMPAPI_STATUS status = SNMPAPI_SUCCESS;
	//System::IntPtr iptrName	= System::Runtime::InteropServices::Marshal::StringToHGlobalUni(temp);
	//char* pIPAddress= reinterpret_cast<char*>(iptrName.ToPointer());
	char* pIPAddress = (char*)(void*)System::Runtime::InteropServices::Marshal::StringToHGlobalAnsi(IPAddress);
	this->m_hEntity = SnmpStrToEntity(hSession, pIPAddress);
	// Frees memory previously allocated from the unmanaged memory of the process.
	System::Runtime::InteropServices::Marshal::FreeHGlobal((System::IntPtr)pIPAddress);

	if(this->m_hEntity == SNMPAPI_FAILURE)
	{
		status = SnmpGetLastError(hSession);
		SNMPManager::ErrorManage(status);
	}

	// set timeout.
	status = SnmpSetTimeout(this->m_hEntity, timeout);
	if(status != SNMPAPI_SUCCESS)
	{
		status = SnmpGetLastError(NULL);
		SNMPManager::ErrorManage(status);
	}

	// set retry.
	status = SnmpSetRetry(this->m_hEntity, retry);
	if(status != SNMPAPI_SUCCESS)
	{
		status = SnmpGetLastError(NULL);
		SNMPManager::ErrorManage(status);
	}
}

System::String^ Entity::EntityToString(HSNMP_ENTITY m_hEntity, HSNMP_SESSION hSession)
{
	char entity[IP_ADDRESS_BUFFER_SIZE];
	SNMPAPI_STATUS status = SnmpEntityToStr(m_hEntity, sizeof(entity), entity);
	if(status == SNMPAPI_FAILURE)
	{
		status = SnmpGetLastError(hSession);
		SNMPManager::ErrorManage(status);
	}
	return gcnew System::String(entity);
}